<?php

/**
 * 后台策略
 */

namespace AdminBundle\Services;

use AdminBundle\Controller\AdminController;

class AdminStrategy extends AdminController
{
    public  $session_return_url  = 'ADMIN_SESSION_RETURN_URL';
    private $session_mark = 'ADMIN_SESSION_MARK';

    /**
     * 设置Url标记
     *
     * 1：主要用于记录主要模块的根节点,以方便页面之前的跳转
     * 2：设置标记同时也会设置菜单标记
     *
     * @param null $mark  标记名
     */
    public function setUrlMark($mark = null)
    {
        $data = array(
            $this->session_return_url => $this->get('unicorn.request')->getCurrentUrl(),
            $this->session_mark => $mark
        );

        $this->get('unicorn.sessions')->set($data);
        $this->setMenuTag($mark);
    }

    /**
     * 设置菜单栏标记
     *
     * 主要用于后台侧边栏的展开关闭
     *
     * @param $menu_tag
     */
    public function setMenuTag($menu_tag)
    {
        self::$request->request->set('menu_tag', $menu_tag);
        self::$request->request->set('session_return_url_name', $this->get('unicorn.sessions')->getName($this->session_return_url));
        self::$request->request->set('session_return_url', $this->get('unicorn.sessions')->get($this->session_return_url));
    }

    /**
     * 得到标记
     *
     * @return mixed
     */
    public function getMark()
    {
        return $this->get('unicorn.sessions')->get($this->session_mark);
    }

    /**
     * 得到回跳的url
     *
     * @return mixed
     */
    public function getReturnUrl()
    {
        return $this->get('unicorn.sessions')->get($this->session_return_url);
    }

    /**
     * 分页
     *
     * @param $total
     * @param array $data
     * @param string $route
     * @return array
     */
    public function paging($total, $data = array(), $route = '')
    {
        $url = '';

        $route = empty($route) ? $this->get('unicorn.request')->getCurrentRouteName() : $route;

        $get_array = $_GET;
        foreach ($get_array as $index => $value) {
            $index = $this->get('unicorn.filters')->quotes($index);
            $value = $this->get('unicorn.filters')->quotes($value);
            if ($index != 'page') {
                $url .= '&' . $index . '=' . $value;
            }
        }
        $page = self::$request->get('page');
        $pagination = new Pagination();
        $pagination->total = $total;
        $pagination->page = $page;
        $pagination->limit = self::$request->get('rows');
        $pagination->url = $this->generateUrl($route) . '?page={page}' . $url;

        $render = $pagination->render();

        $url =  $this->get('unicorn.filters')->quotes($this->generateUrl($route) . '?page=' . $page . $url);

        $data['paging'] = array('render' => $render, 'url' => $url);

        return $data;
    }

    /**
     * 得到导出的路由
     *
     * @param array $data
     * @param string $route
     * @return array
     */
    public function getExUrl($data = array(), $route = '')
    {
        $param = '?ex=1';

        $get_array = $_GET;
        foreach ($get_array as $index => $value) {
            if ($index != 'page' && $index != 'limit' && $index != 'ex') {
                $param .= '&' . $index . '=' . $value;
            }
        }

        if(empty($route)){
            $route = self::$request->getCurrentRouteName();
        }

        $data['ex_url'] = $this->getUrl($route) . $this->get('unicorn.filters')->quotes($param);

        return $data;
    }

    /**
     * 数组导出服务
     *
     * @param string $title 标题
     * @param array $column_info 列表数据 一维数组
     * @param array $rows_info 行数据  二维数组
     * @param int $is_need  是否插入序号
     * @return string  错误信息
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function export($title, $column_info, $rows_info, $is_need)
    {

        if(empty($title)){
            return '标题不能为空';
        }else{
            $title = $this->exFileName($title);
        }

        if(!is_array($column_info) || !is_array($rows_info)){
            return '参数解析不为数组';
        }


        $column_info = array_values($column_info);
        $rows_info = array_values($rows_info);

        foreach ($rows_info as $index => $value){
            $rows_info[$index] = array_values($value);
        }

        //是否需要插入序号
        if($is_need == 1){
            array_unshift($column_info, '序号');
            $i = 1;
            foreach ($rows_info as $index => $value){
                if(!is_array($value)){
                    return '行对象必须为2维数组';
                }
                foreach ($value as $val){
                    if(is_array($val)){
                        return '行对象最多2层';
                    }
                }
                array_unshift($rows_info[$index], $i);
                $i++;
            }
        }

        $PHPExport = new \PHPExcel();
        $properties = $PHPExport->getProperties();
        $properties->setCreator($title);
        $properties->setLastModifiedBy($title);
        $properties->setTitle($title);

        $column = $PHPExport->setActiveSheetIndex(0);
        foreach ($column_info as $index => $value) {
            if(is_array($value)){
                return '列对象需为一维数组';
            }
            $column->setCellValue($this->get('unicorn.string')->stringFromColumnIndex($index).'1', $value);
        }

        foreach ($rows_info as $key => $value){
            $rows = $PHPExport->setActiveSheetIndex(0);
            foreach ($column_info as $index => $val){
                $rows->setCellValueExplicit($this->get('unicorn.string')->stringFromColumnIndex($index). ($key + 2), $this->get('services.arrays')->value($value, $index, ''), \PHPExcel_Cell_DataType::TYPE_STRING);
            }
        }


        $PHPExport->setActiveSheetIndex(0);

        $writer = \PHPExcel_IOFactory::createWriter($PHPExport, 'Excel5');

        $fileName = $title . date('YmdHis');
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="' . $fileName . '.xls"');
        header('Cache-Control: max-age=0');

        $writer->save('php://output');

        return '';
    }

    /**
     * 导出名称处理
     *
     * @param $name
     * @return string
     */
    private function exFileName($name)
    {
        $http_user_agent = $_SERVER['HTTP_USER_AGENT'];

        if(preg_match('/MSIE/i', $http_user_agent)){
            $name = urlencode($name);
        }

        return iconv('UTF-8', 'GBK//IGNORE', $name);
    }
}